//
//  NKNetworkManager.m
//  NKMapTest
//
//  Created by SongGang on 2017/4/11.
//  Copyright © 2017年 NK. All rights reserved.
//

#import "NKNetworkManager.h"

@implementation NKNetworkManager

+ (instancetype)shareInstance {

    static NKNetworkManager *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        instance = [[super alloc] init];
        // 获取AFN原有的数据解析类型 然后新增一些响应解析器能够接受的数据类型
        NSMutableSet *acceptableContentTypes = [NSMutableSet setWithSet:instance.responseSerializer.acceptableContentTypes];
        [acceptableContentTypes addObjectsFromArray:@[@"application/json", @"text/json", @"text/javascript",@"text/html",@"plant/html",@"text/plain",@"text/xml"]];
        instance.responseSerializer.acceptableContentTypes = acceptableContentTypes;
        
    });
    
    return instance;
}

// 网络请求
- (void)requestType:(REQUESTTYPE)requestType withUrlString: (NSString *_Nullable)urlString parames:(id)parames success:(void (^)(id))success failure:(void (^)(id))failure {

//    NSString *uRLString = [self urlStringWithRequestUrlType:urlType];
    //AFN没有做UTF8转码 防止URL字符串中含有中文或特殊字符发生崩溃
    urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"`#%^{}\"[]|\\<> "].invertedSet];
    // get请求
    if (requestType == REQUESTTYPEGET) {
        
        [self GET:urlString parameters:parames progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            success(responseObject);
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            failure(error);
            
        }];
    // post请求
    }else {
    
        [self POST:urlString parameters:parames progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            success(responseObject);
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
             failure(error);
            
        }];
        
    }
}

// 网络上传
- (void)uploadWithUrlString: (NSString *_Nullable)urlString parameters:(id)parameters uploadFileUrl:(NSURL *)fileUrl fileName:(NSString *)fileName progress:(void (^)(NSProgress * _Nullable))progress success:(void (^)(id _Nullable))success failure:(void (^)(NSError * _Nullable))failure {

    //AFN没有做UTF8转码 防止URL字符串中含有中文或特殊字符发生崩溃
    urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"`#%^{}\"[]|\\<> "].invertedSet];
    
    [self POST:urlString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        [formData appendPartWithFileURL:fileUrl name:@"uploadFiles" fileName:fileName mimeType:@"zip" error:nil];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        progress(uploadProgress);
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        success(responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        failure(error);
        
    }];
}

// 网络下载
- (void)downLoadWithUrl: (NSString *_Nullable)urlstring parameters:(id)parameters destinationUrl:(NSString *)destinationUrl progerss:(void (^)(NSProgress * _Nullable))progress success:(void (^)(NSURL * _Nullable))success failure:(void (^)(NSError * _Nullable))failure {
    
    //AFN没有做UTF8转码 防止URL字符串中含有中文或特殊字符发生崩溃
    urlstring = [urlstring stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"`#%^{}\"[]|\\<> "].invertedSet];
    
    NSURLRequest *request = [NSURLRequest requestWithURL: [NSURL URLWithString:urlstring]];
    
    NSURLSessionDownloadTask *downLoadTask = [self downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        
        if (progress) {
            
            progress(downloadProgress);
        }
        
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        
        return [NSURL fileURLWithPath:[destinationUrl stringByAppendingPathComponent:response.suggestedFilename]];
        
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        
        if (error) {
            
            if (failure) {
                
                failure(error);
            }
        }else {
        
            if (success) {
                
                success(filePath);
                
            }
        }
        
    }];
    
    [downLoadTask resume];
}

//- (NSString *)urlStringWithRequestUrlType: (REQUESTURLTYPE)urlType {
//
//    NSString *urlString = @"";
//    
//    if (urlType == REQUESTURLTYPEDOWNZIP) {
//        
//        urlString = [urlString stringByAppendingString:@"http://120.27.247.37:19121/download"];
//    }
//    
//    return urlString;
//}

@end
